package com.liaoyoule.multiple.controller;


import com.alibaba.fastjson.JSONArray;
import com.liaoyoule.multiple.api.ApiResponseMessage;
import com.liaoyoule.multiple.api.UserApi;
import com.liaoyoule.multiple.dao.page.PageInfo;
import com.liaoyoule.multiple.dto.UserDTO;
import com.liaoyoule.multiple.query.MultipleQuery;
import com.liaoyoule.multiple.service.UserService;
import com.liaoyoule.multiple.vm.LoginVM;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-02-20T03:06:37.408Z")

@Controller
public class UserApiController implements UserApi {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    public ResponseEntity<UserDTO> getDatabaseByCode(@ApiParam(value = "id",required=true ) @PathVariable("id") String id) {
        // do some magic!
        return new ResponseEntity<UserDTO>(HttpStatus.OK);
    }

    public ResponseEntity<PageInfo<UserDTO> > getUsers(
            @ApiParam(value = "查询条件") @RequestParam(value = "queryConditon", required = false) String queryString,
            @ApiParam(value = "页码") @RequestParam(value = "pageNumber", required = false,defaultValue = "0") Integer pageNumber,
        @ApiParam(value = "分页大小") @RequestParam(value = "pageSize", required = false,defaultValue = "10") Integer pageSize,
        @ApiParam(value = "排序字段") @RequestParam(value = "orderBy", required = false,defaultValue = "id") String orderBy,
        @ApiParam(value = "排序方式：desc  倒序， asc 升序") @RequestParam(value = "sort", required = false ,defaultValue = "desc") String sort) {


        List<MultipleQuery> multipleQuery = StringUtils.isBlank(queryString) ? Collections.<MultipleQuery>emptyList():JSONArray.parseArray(queryString, MultipleQuery.class);
        // do some magic!
        PageInfo<UserDTO> pageInfo =userService.listPageinfo(multipleQuery, pageNumber, pageSize, new Sort(sort.equalsIgnoreCase("desc") ? Sort.Direction.DESC : Sort.Direction.ASC, orderBy));

        return new ResponseEntity<PageInfo<UserDTO>>(pageInfo,HttpStatus.OK);
    }

    public ResponseEntity<ApiResponseMessage> updateUser(@ApiParam(value = "用户ID",required=true ) @PathVariable("id") String id) {
        // do some magic!


        return new ResponseEntity<ApiResponseMessage>(HttpStatus.OK);
    }

    public ResponseEntity<ApiResponseMessage> userAuthorityPost(@ApiParam(value = "The login certificate JSON you want to post" ,required=true ) @RequestBody LoginVM login) {
        // do some magic!
        UsernamePasswordToken token = new UsernamePasswordToken(login.getAccount(), login.getPassword());
        token.setRememberMe(true);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
        } catch (AuthenticationException e) {
            System.err.println(e.getMessage());
            ApiResponseMessage apiResponseMessage = new ApiResponseMessage(401,"账户或密码错误");
            return new ResponseEntity<ApiResponseMessage>(apiResponseMessage,HttpStatus.OK);
        }
        ApiResponseMessage apiResponseMessage = new ApiResponseMessage(200,"登录成功");
        return new ResponseEntity<ApiResponseMessage>(apiResponseMessage,HttpStatus.OK);
    }

    @Override
    @RequiresPermissions("")
    public ResponseEntity<ApiResponseMessage> userDelete(@ApiParam(value = "1,2,3,4", required = true) @PathVariable("id") String id) {

        if(StringUtils.isBlank(id)){
            return new ResponseEntity<ApiResponseMessage>(HttpStatus.BAD_REQUEST);
        }
        String[] ids = id.split(",");
        List<String> idList = Arrays.asList(ids);
        userService.batchDelete(idList);
        return new ResponseEntity<ApiResponseMessage>(HttpStatus.OK);
    }

    @Override
    public ResponseEntity userDownload(@ApiParam(value ="1,2,3,4", required = true) @RequestBody String id,HttpServletResponse response) {
        // do some magic!
        String[] split = id.split(",");
        List<MultipleQuery> multipleQueries = new ArrayList<>();
        Arrays.stream(split).forEach(p->{
            MultipleQuery multipleQuery = new MultipleQuery();
            multipleQuery.setField("id");
            multipleQuery.setValue(p);
            multipleQuery.setAndOr(false);
            multipleQueries.add(multipleQuery);
        });
        PageInfo<UserDTO> pageInfo = userService.listPageinfo(multipleQueries, 0, 10, new Sort( Sort.Direction.DESC , "id"));
        List<UserDTO> list = pageInfo.getList();

        List<UserDTO> excelDates = new ArrayList<>();
        list.forEach((UserDTO p) ->
                {excelDates.add(p);}
        );
        response.reset();
        String fileName = "用户-" + new Date().getTime() + ".xls";
        try {
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/msexcel");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            ServletOutputStream out = response.getOutputStream();
            //下面是对中文文件名的处理
            //下面是对中文文件名的处理
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), UserDTO.class, excelDates);
            workbook.write(response.getOutputStream());
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 确保发送的当前文本格式
        return new ResponseEntity(HttpStatus.OK);

    }


}
